<template>
  <div>
    <el-button type="primary" @click="showSearchByIdDialog">根据ID查询拍卖活动</el-button>
    <el-button type="primary" @click="showSearchByConditionsDialog">条件搜索拍卖活动</el-button>
    <el-button type="primary" @click="handleReset">重置所有搜索</el-button>

    <!-- 在表格中显示拍卖活动 -->
    <el-table :data="auctionList" stripe border>
      <el-table-column label="拍卖ID" prop="id"></el-table-column>
      <el-table-column label="车辆ID" prop="carId"></el-table-column>
      <el-table-column label="开始时间" prop="startTime"></el-table-column>
      <el-table-column label="结束时间" prop="endTime"></el-table-column>
      <el-table-column label="起拍价格" prop="startingPrice"></el-table-column>
      <el-table-column label="加价幅度" prop="increaseAmount"></el-table-column>
      <el-table-column label="当前价格" prop="currentPrice"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="showCarInfo(scope.row.carId)">查看车辆信息</el-button>
          <el-button type="text" @click="showBidDialog(scope.row.id, scope.row.carId)">出价</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 拍卖活动的分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    >
    </el-pagination>

    <!-- 根据ID查询对话框 -->
    <el-dialog
        title="根据ID查询拍卖活动"
        :visible.sync="searchByIdDialogVisible"
        width="30%"
    >
      <el-form :model="searchByIdForm" inline>
        <el-form-item label="拍卖ID">
          <el-input v-model="searchByIdForm.id" placeholder="请输入拍卖ID"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getAuctionById">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 条件搜索对话框 -->
    <el-dialog
        title="条件搜索拍卖活动"
        :visible.sync="searchByConditionsDialogVisible"
        width="50%"
    >
      <el-form :model="searchByConditionsForm" inline>
        <el-form-item label="开始时间">
          <el-input v-model="searchByConditionsForm.startTime" placeholder="请输入开始时间"></el-input>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-input v-model="searchByConditionsForm.endTime" placeholder="请输入结束时间"></el-input>
        </el-form-item>
        <el-form-item label="起拍价格">
          <el-input v-model.number="searchByConditionsForm.startingPrice" placeholder="请输入起拍价格"></el-input>
        </el-form-item>
        <el-form-item label="加价幅度">
          <el-input v-model.number="searchByConditionsForm.increaseAmount" placeholder="请输入加价幅度"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchAuctionByConditions">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 汽车信息弹窗 -->
    <el-dialog title="车辆信息" :visible.sync="carInfoDialogVisible" width="50%">
      <el-table :data="carInfoList" stripe border>
        <el-table-column label="车辆图片" width="120">
          <template slot-scope="scope">
            <!-- 检查图片数组是否存在，且不为空 -->
            <img v-if="scope.row.imgs && scope.row.imgs.length > 0" :src="scope.row.imgs[0].imageUrl" class="avatar">
          </template>
        </el-table-column>
        <el-table-column label="车辆编号" prop="id"></el-table-column>
        <el-table-column label="品牌" prop="brand"></el-table-column>
        <el-table-column label="型号" prop="model"></el-table-column>
        <el-table-column label="年份" prop="year"></el-table-column>
        <el-table-column label="里程数" prop="mileage"></el-table-column>
        <el-table-column label="颜色" prop="color"></el-table-column>
        <el-table-column label="车辆状况描述" prop="conditionDescription"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 修改出价对话框 -->
    <el-dialog
        title="请输入修改的价格"
        :visible.sync="bidDialogVisible"
        width="30%">

      <el-form :model="bidForm" inline>
        <el-form-item class="bid-price" label="我的出价">
          <span v-if="currentBidPrice">{{ currentBidPrice }}</span>
          <span v-else>暂无出价</span>
        </el-form-item>

        <el-form-item class="bid-input">
          <el-input v-model="bidForm.price" placeholder="请输入价格"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleModifyBid(bidForm.price)">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';
import {Message, Loading} from 'element-ui';

export default {
  data() {
    return {
      searchByIdDialogVisible: false,
      searchByConditionsDialogVisible: false,
      bidDialogVisible: false,
      searchByIdForm: {id: ''},
      searchByConditionsForm: {
        startTime: '',
        endTime: '',
        startingPrice: null,
        increaseAmount: null,
      },
      bidForm: {price: null},
      auctionList: [],
      carInfoList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loadingInstance: null,
      carInfoDialogVisible: false,
      currentActivityId: null,
      currentCarId: null,
      myBidPrices: {}, // 定义 myBidPrices 属性
      bidCounts: {}, // 存储每个订单的出价次数
      maxBidCount: 3, // 最大出价次数限制
      currentBidPrice: null, // 当前拍卖活动的我的出价
    };
  },
  created() {
    this.loadAuctionData();
  },
  methods: {
    async loadAuctionData() {
      this.loadingInstance = Loading.service({fullscreen: true});
      try {
        const response = await axios.get('/api/auction/blist');
        if (response.data.code === 200) {
          const auctionList = response.data.data.list;
          await this.updateCurrentPrices(auctionList);
          this.auctionList = auctionList;
          this.total = response.data.data.total;
        } else {
          Message.error('获取拍卖活动失败');
        }
      } catch (error) {
        Message.error('没有拍卖活动');
      } finally {
        if (this.loadingInstance) {
          this.loadingInstance.close();
        }
      }
    },
    async getAuctionById() {
      const id = this.searchByIdForm.id;
      if (!id) {
        Message.warning('请输入拍卖ID');
        return;
      }

      const response = await axios.get(`/api/auction/getById?id=${id}`);
      if (response.data.code === 200) {
        const auction = response.data.data;
        await this.updateCurrentPrices([auction]);
        this.auctionList = [auction];
        this.total = 1;
        this.searchByIdDialogVisible = false;
      } else {
        Message.error('获取拍卖活动失败');
      }
    },
    async searchAuctionByConditions() {
      const params = {
        startTime: this.searchByConditionsForm.startTime,
        endTime: this.searchByConditionsForm.endTime,
        startingPrice: this.searchByConditionsForm.startingPrice,
        increaseAmount: this.searchByConditionsForm.increaseAmount,
      };

      const response = await axios.get(`/api/auction/normal/list`, {params});
      if (response.data.code === 200) {
        const auctionList = response.data.data.list;
        await this.updateCurrentPrices(auctionList);
        this.auctionList = auctionList;
        this.total = response.data.data
            .total;
        this.searchByConditionsDialogVisible = false;
      } else {
        Message.error('获取拍卖活动失败');
      }
    },
    async updateCurrentPrices(auctionList) {
      for (let item of auctionList) {
        const response = await axios.get('/api/user/activity/getLatestBid', {
          params: {
            actId: item.id
          }
        });
        if (response.data.code === 200) {
          item.currentPrice = response.data.data || null;
          item.bidPrice = response.data.data || null;
        } else {
          item.currentPrice = null;
        }
      }
    },
    async showCarInfo(carId) {
      try {
        const response = await axios.get(`/api/car/getById?carId=${carId}`);
        if (response.data.code === 200) {
          this.carInfoList = response.data.data.list;
          this.carInfoDialogVisible = true;
        } else {
          Message.error('获取车辆信息失败');
        }
      } catch (error) {
        Message.error('请求失败，请稍后重试');
      }
    },
    showSearchByIdDialog() {
      this.searchByIdDialogVisible = true;
    },
    showSearchByConditionsDialog() {
      this.searchByConditionsDialogVisible = true;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadAuctionData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadAuctionData();
    },
    handleReset() {
      this.searchByIdForm.id = '';
      this.searchByConditionsForm.startTime = '';
      this.searchByConditionsForm.endTime = '';
      this.searchByConditionsForm.startingPrice = null;
      this.searchByConditionsForm.increaseAmount = null;
      this.loadAuctionData();
    },
    showBidDialog(activityId, carId) {
      this.currentActivityId = activityId;
      this.currentCarId = carId;
      // eslint-disable-next-line no-prototype-builtins
      if (!this.bidCounts.hasOwnProperty(activityId)) {
        this.$set(this.bidCounts, activityId, 0);
      }
      this.bidDialogVisible = true;
      this.currentBidPrice = this.auctionList.find(auction => auction.id === activityId)?.bidPrice || null;
    },
    async handleModifyBid(price) {
      try {
        const response = await axios.post(`/api/user/activity/bid`, {
          actId: this.currentActivityId,
          carId: this.currentCarId,
          price: price,
        });
        if (response.status === 200) {
          if (response.data.code === 200) {
            // 更新 myBidPrices 中当前拍卖活动的我的出价
            this.$set(this.myBidPrices, this.currentActivityId, price);

            // 更新当前拍卖活动的我的出价
            this.currentBidPrice = price;

            // 更新 auctionList 中的出价价格和当前价格
            const auctionIndex = this.auctionList.findIndex(
                (auction) => auction.id === this.currentActivityId
            );
            if (auctionIndex !== -1) {
              this.$set(this.auctionList, auctionIndex, {
                ...this.auctionList[auctionIndex],
                bidPrice: price,
                currentPrice: price,
              });
            }
            Message.success('出价成功');
            this.bidDialogVisible = false;
          } else if (response.data.code === 5003) {
            Message.error(`出价不符合最低出价要求（当前价格 + 出价幅度）`);
          } else if (response.data.code === 500) {
            Message.error('出价次数超过限制！最多出价三次！');
          }
        } else {
          Message.error('请求失败，请稍后重试');
        }
      } catch (error) {
        Message.error('请求失败，请稍后重试');
      }
    },
  },
};
</script>

<style scoped>
.avatar {
  width: auto;
  height: 80px;
}
.bid-price,
.bid-input {
  display: block;
  margin-bottom: 10px; /* 根据需要调整间距 */
}
</style>
